/* 
Scenic Graphics Library
Copyright (C) 2007 Jouni Tulkki

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USApackage scenic;
*/

#ifndef Scenic_Renderer_Resource_h
#define Scenic_Renderer_Resource_h


#include <jni.h>

#include "DynArray.h"


namespace Scenic
{
namespace Renderer
{
	
class CriticalSection
{
#ifdef WIN32
	CRITICAL_SECTION criticalSection;
#else
	pthread_mutex_t mutex;
#endif
	int lockCount;
public:
	CriticalSection();
	virtual ~CriticalSection();

	int enterCriticalSection();
	int leaveCriticalSection();
	
	virtual void onEnter();
	virtual void onLeave();
};

class Synchronized
{
	CriticalSection *criticalSection;
public:
	Synchronized(CriticalSection *criticalSection) 
	{ 
		this->criticalSection = criticalSection;
		this->criticalSection->enterCriticalSection(); 
	}
	Synchronized(CriticalSection &criticalSection) 
	{ 
		this->criticalSection = &criticalSection;
		this->criticalSection->enterCriticalSection(); 
	}
	~Synchronized()
	{
		criticalSection->leaveCriticalSection();
	}
};

class Resource;

class ResourcePool : public CriticalSection
{
public:
	const char *name;
	bool debug;
	DynArray<Resource*> pool;
	int numItems;

public:
	ResourcePool(const char *name, bool debug = false);

	Resource *get(int id);
	DynArray<Resource*> &getAll() { return pool; }
	void add(Resource *resource);
	void remove(Resource *resource);

};

class JNIEnvPtr
{
	JavaVM *vm;
	bool detach;
	JNIEnv *env;
public:

	JNIEnvPtr(JavaVM *vm);
	~JNIEnvPtr();

	JNIEnv *getEnv() { return env; }
	JNIEnv *operator->() { return env; }
};

class Resource : public CriticalSection
{
	int debug;
	int refCount;
	JavaVM *javaVm;
	jobject javaObject;
	int javaObjectRefCount;
public:
	int id;
	ResourcePool *pool;

	Resource(ResourcePool *pool);
	virtual ~Resource();

	void addRef() { refCount++; }
	void release();

	jobject getJavaObject() { return javaObject; }
	JavaVM *getJavaVM() { return javaVm; }
	void addReference(JNIEnv *env, jobject localObject);
	void addReference(JavaVM *vm, jobject localObject);
	void releaseReference();
};

}
}

#endif
